package cn.rwklyd.BookKeeping.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.node.TextNode;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * 自定义LocalDateTime反序列化器，支持多种格式：
 * 1. 标准格式字符串 "yyyy-MM-dd HH:mm:ss"
 * 2. 秒级时间戳
 */
public class LocalDateTimeConverter extends JsonDeserializer<LocalDateTime> {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final ZoneId ZONE_ID = ZoneId.of("Asia/Shanghai");

    @Override
    public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String value = p.getValueAsString();
        
        // 如果为空，返回null
        if (value == null || value.isEmpty()) {
            return null;
        }
        
        try {
            // 尝试解析为标准格式
            return LocalDateTime.parse(value, FORMATTER);
        } catch (DateTimeParseException e1) {
            try {
                // 尝试解析为ISO格式
                return LocalDateTime.parse(value);
            } catch (DateTimeParseException e2) {
                try {
                    // 尝试解析为时间戳（秒）
                    long timestamp = Long.parseLong(value);
                    return LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZONE_ID);
                } catch (NumberFormatException e3) {
                    throw new IOException("无法解析日期时间: " + value, e3);
                }
            }
        }
    }
} 